#coding: utf8
import re
import locale
from pygeocoder import Geocoder
import time
import urlparse
from decimal import Decimal
from datetime import datetime
from items import RestaurantItem
from items import RestaurantReview

class FourSqrUtils(object):

    utils = None
    dictMeses = {"enero": "01/","febrero":"02/","marzo":"03/","abril":"04/","mayo":"05/","junio":"06/","julio":"07/","agosto":"08/","septiembre":"09/","octubre":"10/","noviembre":"11/","diciembre":"12/"}

    def fillRestaurant(self,client,restaurant):
        try:
            venue = client.venues(restaurant['id_venue'])
            if venue is not None:
                restaurant['url_scrapy']=str(venue['venue']['canonicalUrl'])
                restaurant['reviews_total'] = str(venue['venue']['stats']['tipCount'])
                restaurant['check_ins'] = str(venue['venue']['stats']['checkinsCount'])
                restaurant['visitors']= str(venue['venue']['stats']['usersCount'])
                restaurant['reviews'] = []              
                restaurant['restaurant_name'] = str(venue['venue']['name'])
                address0 = str(venue['venue']['location']['address'])
                address1 = str(venue['venue']['location']['city'])
                restaurant['address'] = address0 + ", " + address1 
                restaurant['address_google'] = self.utils.getRestAddressGoogleReady(restaurant['address'])
                restaurant['phone']=None
                if "phone" in venue['venue']['contact']:
                    restaurant['phone'] = str(venue['venue']['contact']['phone'])
                restaurant['cp']= str(venue['venue']['location']['postalCode'])
                restaurant['score']=Decimal(str(venue['venue']['rating']))
               
                restaurant['mayorID']=None
                restaurant['mayorPhoto']=None
                restaurant['mayorUrl']=None
                if "mayor" in venue['venue']:
                    restaurant['mayorID']=str(venue['venue']['mayor']['user']['id'])
                    restaurant['mayorUrl'] = 'https://www.foursquare.com/user/'+restaurant['mayorID']
                    lastName=''
                    if 'lastName' in venue['venue']['mayor']['user']:
                        lastName=str(venue['venue']['mayor']['user']['lastName'])
                    name=''
                    if 'firstName' in venue['venue']['mayor']['user']:
                        name=str(venue['venue']['mayor']['user']['firstName'])
                    restaurant['mayorName'] = name + " " + lastName
                    if 'photo' in venue['venue']['mayor']['user']:
                        restaurant['mayorPhoto'] = self.__getUserPhoto(venue['venue']['mayor']['user']['photo'])                    
                restaurant['url_rest']=None
            else:
                self.utils.logProcessDetail("FourSquare con not get venue for code: " + restaurant['url_scrapy']+ " source_rest_id: " + restaurant['idRestSource'],self.utils.ERROR)
                
            return
        except Exception,e:
            self.utils.logProcessDetail("Error in fillRestaurant from response: " + str(e),self.utils.ERROR)
          
    def __getUserPhoto(self,dict):
        try:
            tmpStr = str(dict['prefix'])+'48x48'+str(dict['suffix'])
            #tmpUrl = urlparse.urljoin(tmpStr,'/48x48/')
            #tmpUrl = urlparse.urljoin(str(tmpUrl),str(dict['suffix']))
            return tmpStr.strip()
        except Exception,e:
            self.utils.logProcessDetail("Error in __getUserPhoto: " + str(e),self.utils.ERROR)

    def fillRestaurantComments(self,client,restaurant):
        try:
            restaurantReview = None
            tips = client.venues.tips(restaurant['id_venue'],{'sort': 'recent','limit':'500'})
            if tips is not None:
                for i in range(int(tips['tips']['count'])):
                    restaurantReview = RestaurantReview()
                    restaurantReview['reviewID']=str(tips['tips']['items'][i]['id'])
                    lastName=''
                    if 'lastName' in tips['tips']['items'][i]['user']:
                        lastName=str(tips['tips']['items'][i]['user']['lastName'])
                    name=''
                    if 'firstName' in tips['tips']['items'][i]['user']:
                        name=str(tips['tips']['items'][i]['user']['firstName'])
                    restaurantReview['author'] = name + " " + lastName
                    restaurantReview['authorID'] =str(tips['tips']['items'][i]['user']['id'])
                    restaurantReview['authorURL'] = 'https://www.foursquare.com/user/'+restaurantReview['authorID']
                    restaurantReview['authorPhoto']=None
                    if 'photo' in tips['tips']['items'][i]['user']:
                        restaurantReview['authorPhoto']=self.__getUserPhoto(tips['tips']['items'][i]['user']['photo'])
                    restaurantReview['date'] = self.__getCommentDate(tips['tips']['items'][i]['createdAt'])
                    restaurantReview['comment'] = str(tips['tips']['items'][i]['text'].encode("utf-8",'ignore'))
                    #.decode('utf-8', 'ignore')
                    restaurant['reviews'].append(restaurantReview)
            else:
                self.utils.logProcessDetail("FourSquare con not get tips for code: " + restaurant['url_scrapy']+ " source_rest_id: " + restaurant['idRestSource'],self.utils.ERROR)
                
            return restaurantReview


        except Exception,e:
            self.utils.logProcessDetail("Error in fillRestaurantComment: " + str(e),self.utils.ERROR)


    def __getCommentDate(self,inDate):
        try:
            dDate=None
            stTime=None
            if inDate is not None:
                stTime = time.gmtime(inDate)
                tmp_s = time.strftime('%d/%m/%Y',stTime)
            return tmp_s
    
        except Exception,e:
            self.utils.logProcessDetail("Error in __getCommentDate: " + str(e) + "date: " + str(inDate),self.utils.ERROR)

        